<template>
  <view class="home-page">
    <!-- 顶部城市选择和搜索 -->
    <view class="header">
      <view class="city-selector" @click="showCityPicker">
        <text class="city-name">{{ currentCity }}</text>
        <at-icon value="chevron-down" size="16" color="#fff"></at-icon>
      </view>
      <view class="search-box" @click="goToSearch">
        <at-icon value="search" size="16" color="#999"></at-icon>
        <text class="search-placeholder">搜索课程或商家</text>
      </view>
      <view class="notification" @click="goToNotification">
        <at-icon value="bell" size="20" color="#fff"></at-icon>
      </view>
    </view>

    <!-- Banner广告位 -->
    <view class="banner-section">
      <swiper 
        class="banner-swiper" 
        :indicator-dots="true" 
        :autoplay="true" 
        :interval="3000"
        indicator-color="rgba(255,255,255,0.5)"
        indicator-active-color="#fff"
      >
        <swiper-item v-for="(banner, index) in banners" :key="index">
          <view class="banner-item" @click="onBannerClick(banner)">
            <!-- 当有image字段时显示图片，否则显示SVG图标 -->
            <image v-if="banner.image" :src="banner.image" class="banner-image" mode="aspectFill" />
            <SvgIcon v-else :icon-class="banner.iconClass" class="banner-image" width="100%" height="100%" />
            <view class="banner-content">
              <text class="banner-title">{{ banner.title }}</text>
              <text class="banner-subtitle">{{ banner.subtitle }}</text>
              <view class="banner-btn">{{ banner.buttonText }}</view>
            </view>
          </view>
        </swiper-item>
      </swiper>
    </view>

    <!-- 课程分类 -->
    <view class="category-section">
      <view class="section-title">课程分类</view>
      <view class="category-row">
        <view 
          v-for="category in displayCategories" 
          :key="category.id" 
          class="category-item"
          @click="goToCategory(category)"
        >
          <view class="category-icon">
            <DynamicSvgIcon :svg-code="category.icon" class="icon-image" width="48px" height="48px" />
          </view>
          <text class="category-name">{{ category.name }}</text>
        </view>
      </view>
    </view>

    <!-- 热门推荐 -->
    <view class="recommend-section">
      <view class="section-header">
        <text class="section-title">热门推荐</text>
        <text class="more-btn" @click="goToCourseList('hot')">更多</text>
      </view>
      <scroll-view class="course-scroll" scroll-x>
        <view class="course-list">
          <view 
            v-for="course in hotCourses" 
            :key="course.id" 
            class="course-card"
            @click="goToCourseDetail(course.id)"
          >
            <image :src="course.coverUrl" class="course-image" mode="aspectFill" />
            <view class="course-info">
              <text class="course-title">{{ course.title }}</text>
              <text class="course-merchant">{{ course.merchantName }}</text>
              <view class="course-footer">
                <text class="course-price">¥{{ course.price }}</text>
                <text class="course-sales">{{ course.salesCount }}人已购</text>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 精选课程 -->
    <view class="featured-section">
      <view class="section-header">
        <text class="section-title">精选课程</text>
        <text class="more-btn" @click="goToCourseList('recommend')">更多</text>
      </view>
      <view class="featured-list">
        <view 
          v-for="course in recommendCourses" 
          :key="course.id" 
          class="featured-item"
          @click="goToCourseDetail(course.id)"
        >
          <image :src="course.coverUrl" class="featured-image" mode="aspectFill" />
          <view class="featured-info">
            <text class="featured-title">{{ course.title }}</text>
            <text class="featured-desc">{{ course.description }}</text>
            <view class="featured-meta">
              <text class="featured-merchant">{{ course.merchantName }}</text>
              <text class="featured-price">¥{{ course.price }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import Taro from '@tarojs/taro'
import courseApi from '@/api/course'
import { showLoading, hideLoading, navigateTo } from '@/utils'
import DynamicSvgIcon from '@/components/DynamicSvgIcon/index.vue'

// 响应式数据
const currentCity = ref('乐陵市')
const banners = ref([])

const categories = ref([])

const hotCourses = ref([])
const recommendCourses = ref([])

// 计算属性
const displayCategories = computed(() => {
  return categories.value.slice(0, 5)
})

// 页面加载
onMounted(() => {
  loadPageData()
})

// 加载页面数据
const loadPageData = async () => {
  try {
    console.log('开始加载页面数据')
    showLoading('加载中...')
    
    console.log('准备调用API接口')
    // 并发请求热门课程、推荐课程、分类数据和横幅广告
    const [hotRes, recommendRes, categoriesRes, bannersRes] = await Promise.all([
      courseApi.getHotCourses(6),
      courseApi.getRecommendCourses(5),
      courseApi.getCourseCategories(),
      courseApi.getHomeBanners(5)
    ])
    
    console.log('API调用完成，热门课程结果：', hotRes)
    console.log('API调用完成，推荐课程结果：', recommendRes)
    console.log('API调用完成，分类结果：', categoriesRes)
    console.log('API调用完成，横幅结果：', bannersRes)
    
    hotCourses.value = hotRes.data || []
    recommendCourses.value = recommendRes.data || []
    
    // 处理横幅数据
    const bannerData = bannersRes.data || []
    banners.value = bannerData.map((banner, index) => ({
      ...banner,
      iconClass: `banner${(index % 3) + 1}`,
      buttonText: '立即查看',
      subtitle: banner.title || '精彩内容等你发现'
    }))
    
    // 处理分类数据，直接使用分类名称生成动态图标
    const categoryData = categoriesRes.data || []
    categories.value = categoryData.map((category, index) => ({
      ...category
      // 不再需要iconClass，DynamicSvgIcon组件会根据category.name自动生成图标
    }))
    
    // 添加"全部分类"选项
    if (categories.value.length > 0) {
      categories.value.push({
        id: 999,
        name: '全部分类',
        iconClass: 'category8'
      })
    }
  } catch (error) {
    console.error('加载页面数据失败:', error)
  } finally {
    hideLoading()
  }
}

// 事件处理
const showCityPicker = () => {
  // TODO: 实现城市选择功能
  Taro.showToast({
    title: '城市选择功能开发中',
    icon: 'none'
  })
}

const goToSearch = () => {
  navigateTo('/pages/search/index')
}

const goToNotification = () => {
  navigateTo('/pages/notification/index')
}

const onBannerClick = (banner) => {
  if (banner.linkUrl) {
    navigateTo(banner.linkUrl)
  }
}

const goToCategory = (category) => {
  navigateTo('/pages/course/list', { categoryId: category.id })
}

const goToCourseList = (type) => {
  navigateTo('/pages/course/list', { type })
}

const goToCourseDetail = (courseId) => {
  navigateTo('/pages/course/detail', { id: courseId })
}
</script>

<style lang="less">
.home-page {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 32px 16px;
  background: linear-gradient(135deg, #3478F6 0%, #5B9BF8 100%);
  color: white;

  .city-selector {
    display: flex;
    align-items: center;
    
    .city-name {
      font-size: 32px;
      font-weight: 500;
      margin-right: 8px;
    }
  }

  .search-box {
    flex: 1;
    display: flex;
    align-items: center;
    background: rgba(255, 255, 255, 0.2);
    border-radius: 40px;
    padding: 16px 24px;
    margin: 0 24px;

    .search-placeholder {
      color: rgba(255, 255, 255, 0.8);
      font-size: 28px;
      margin-left: 16px;
    }
  }

  .notification {
    padding: 8px;
  }
}

.banner-section {
  padding: 24px 32px;

  .banner-swiper {
    height: 320px;
    border-radius: 16px;
    overflow: hidden;
  }

  .banner-item {
    position: relative;
    height: 100%;
    border-radius: 16px;
    overflow: hidden;
  }

  .banner-image {
    width: 100%;
    height: 100%;
  }

  .banner-content {
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(45deg, rgba(52, 120, 246, 0.8), rgba(245, 166, 35, 0.8));
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: white;

    .banner-title {
      font-size: 40px;
      font-weight: bold;
      margin-bottom: 8px;
    }

    .banner-subtitle {
      font-size: 28px;
      margin-bottom: 24px;
    }

    .banner-btn {
      background: white;
      color: #3478F6;
      padding: 16px 32px;
      border-radius: 40px;
      font-size: 28px;
      font-weight: 500;
    }
  }
}

.category-section {
  background: white;
  margin: 0 32px 24px;
  border-radius: 16px;
  padding: 32px 24px;

  .section-title {
    font-size: 32px;
    font-weight: 600;
    color: #333;
    margin-bottom: 32px;
  }

  .category-row {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    gap: 16px;
  }

  .category-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    flex: 1;
    min-width: 0;

    .category-icon {
      width: 80px;
      height: 80px;
      background: #f8f9fa;
      border-radius: 16px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 12px;

      .icon-image {
        width: 40px;
        height: 40px;
      }
    }

    .category-name {
      font-size: 22px;
      color: #666;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      width: 100%;
    }
  }
}

.recommend-section, .featured-section {
  background: white;
  margin: 0 32px 24px;
  border-radius: 16px;
  padding: 32px 0;

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 24px;
    margin-bottom: 32px;

    .section-title {
      font-size: 32px;
      font-weight: 600;
      color: #333;
    }

    .more-btn {
      font-size: 28px;
      color: #3478F6;
    }
  }
}

.course-scroll {
  white-space: nowrap;

  .course-list {
    display: inline-flex;
    padding: 0 24px;
    gap: 24px;
  }

  .course-card {
    width: 280px;
    background: #f8f9fa;
    border-radius: 12px;
    overflow: hidden;
    flex-shrink: 0;

    .course-image {
      width: 100%;
      height: 160px;
    }

    .course-info {
      padding: 24px 20px;

      .course-title {
        font-size: 28px;
        font-weight: 500;
        color: #333;
        display: block;
        margin-bottom: 8px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .course-merchant {
        font-size: 24px;
        color: #999;
        display: block;
        margin-bottom: 16px;
      }

      .course-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .course-price {
          font-size: 32px;
          font-weight: 600;
          color: #F5A623;
        }

        .course-sales {
          font-size: 24px;
          color: #999;
        }
      }
    }
  }
}

.featured-list {
  padding: 0 24px;

  .featured-item {
    display: flex;
    margin-bottom: 32px;
    background: #f8f9fa;
    border-radius: 12px;
    overflow: hidden;

    &:last-child {
      margin-bottom: 0;
    }

    .featured-image {
      width: 200px;
      height: 140px;
      flex-shrink: 0;
    }

    .featured-info {
      flex: 1;
      padding: 24px 20px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      .featured-title {
        font-size: 28px;
        font-weight: 500;
        color: #333;
        margin-bottom: 8px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .featured-desc {
        font-size: 24px;
        color: #666;
        line-height: 1.4;
        margin-bottom: 16px;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
      }

      .featured-meta {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .featured-merchant {
          font-size: 24px;
          color: #999;
        }

        .featured-price {
          font-size: 32px;
          font-weight: 600;
          color: #F5A623;
        }
      }
    }
  }
}
</style>
